package cn.tiger.threadPool;

import java.util.concurrent.*;

/**
 * 简单介绍Callable使用方法
 * callable和runnable的区别
 *
 */
public class CallableDemo {

    public static void main(String[] args) {
        // 创建线程池（使用4个线程）
        ExecutorService executor = Executors.newFixedThreadPool(4);

        // 创建Callable任务
        Callable<Integer> task = new MyCallable(100);

        try {
            // 提交任务至线程池 并获取Future对象
            Future<Integer> future = executor.submit(task);
            System.out.println("线程池方式计算结果: " + future.get());
            executor.shutdown();

            // 提交任务至FurtureTask 并获取结果
            FutureTask<Integer> futureTask = new FutureTask<>(task);
            futureTask.run();
            System.out.println("FurtureTask计算结果: " + futureTask.get());

            //线程池方式计算结果: 101

            //FurtureTask计算结果: 101

        } catch (InterruptedException | ExecutionException e) {
            System.err.println("任务执行异常: " + e.getMessage());
        } finally {
            // 关闭线程池
            executor.shutdown();
        }
    }

    /**
     * 自定义Callable实现类
     * 计算1到n的累加和
     */
    static class MyCallable implements Callable<Integer> {
        private final int n;

        public MyCallable(int n) {
            this.n = n;
        }

        @Override
        public Integer call() throws Exception {
            if (n < 0) {
                throw new IllegalArgumentException("n不能为负数");
            }
            int sum = 0 ;
            sum = n + 1;
            return sum;
        }
    }
}
